from django.shortcuts import render, redirect

from QQLoginTool.QQtool import OAuthQQ
from django.views import View
from django import http
from django.conf import settings
from django.contrib.auth import login
import re
from django_redis import get_redis_connection

from csdp.utils.response_code import RETCODE
from .models import OAuthQQUser
import logging
from users.models import User
from .utils import generate_openid_sign, check_openid

logger = logging.getLogger('django')

# Create your views here.

class QQAuthURLView(View):
    def get(self, request):
        next = request.GET.get('next') or '/'
        auth_qq = OAuthQQ(
            client_id = settings.QQ_CLIENT_ID,
            client_secret = settings.QQ_CLIENT_SECRET,
            redirect_uri = settings.QQ_REDIRECT_URI,
            state = next
        )
        login_url = auth_qq.get_qq_url()
        return http.JsonResponse({'login_url': login_url, 'code': RETCODE.OK, 'errmsg': 'OK'})


class QQAuthView(View):
    def get(self, request):
        code = request.GET.get('code')
        if code is None:
            return http.HttpResponseForbidden('参数错误。')
        auth_qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI
        )
        try:
            access_token = auth_qq.get_access_token(code)
            openid = auth_qq.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('QQ认证失败。')
        try:
            oauth_model = OAuthQQUser.objects.get(openid = 'openid')
            user = oauth_model.user
            login(request, user)
            response = redirect(request.GET.get('state') or '/')
            response.set_cookie('username', user.username, max_age = settings.SESSION_COOKIE_AGE)
            return response
        except OAuthQQUser.DoesNotExist:
            openid = generate_openid_sign(openid)
            return render(request, 'oauth_callback.html', {'openid': openid})

    def post(self, request):
        query_dict = request.POST
        mobile = query_dict.get('mobile')
        password = query_dict.get('password')
        sms_code = query_dict.get('sms_code')
        openid = query_dict.get('openid')
        list0 = query_dict.dict().pop('openid').values()
        if all(list0) is False or len(list0) != 4:
            return http.HttpResponseForbidden('参数错误。')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数错误。')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('参数错误。')
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if sms_code_server is None:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '失效的验证码。'})
        redis_conn.delete('sms_%s' % mobile)
        if sms_code != sms_code_server.decode():
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '失效的验证码。'})
        openid = check_openid(openid)
        if openid is None:
            return render(request, 'oauth_callback.html', {'openid_errmsg': '请求超时。'})
        try:
            user = User.objects.get(mobile =  mobile)
            if user.check_password(password) is False:
                return render(request, 'oauth_callback.html', {'qq_login_errmsg': 'QQ绑定失败。'})
        except User.DoesNotExist:
            user = User.objects.create_user(username = mobile, password = password, mobile = mobile)
        OAuthQQUser.objects.create(user = user, openid = openid)
        login(request, user)
        response = redirect(request.GET.get('state') or '/')
        response.set_cookie('username', user.username, max_age = settings.SESSION_COOKIE_AGE)
        return
